//
//  SYRequestAPI.m
//  SanYiTeaching
//
//  Created by 郑浩然 on 2019/5/2.
//  Copyright © 2019年 SanYi. All rights reserved.
//

#import "SYRequestAPI.h"
#import "LoginViewController.h"
#import "AppDelegate.h"


#define API_TEST 0
#if API_TEST == 1
NSString *const kCMBaseApiURL = @"http://apipad.mykeyu.cn/";//测试环境
NSString *const kPCBaseApiURL = @"http://apipc.mykeyu.cn/";//pc端
NSString *const kBBCMBaseApiURL = @"http://api.mykeyu.cn/ParentClientService.svc/Tencent/";
#else//正式环境
NSString *const kPCBaseApiURL = @"http://apipc.31waiyu.com/";//pc端
NSString *const kCMBaseApiURL = @"http://apipad.31waiyu.com/";
//NSString *const kBBCMBaseApiURL = @"http://api.31waiyu.com/ParentClientService.svc/Tencent/";
NSString *const kBBCMBaseApiURL = @"http://ticpush.31waiyu.com/TicService.svc/Tencent/";

NSString *const kBBTMBaseApiUrl = @"http://ticpush.31waiyu.com/";//获取腾讯录屏相关信息
#endif



@interface SYRequestAPI () {
    AFHTTPSessionManager *_manager;
    AFURLSessionManager *_manage;
}


@end



@implementation SYRequestAPI

#pragma mark - init && setup
+ (SYRequestAPI *)sharedAPI {
    static SYRequestAPI *_sharedRequestAPI = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _sharedRequestAPI = [[SYRequestAPI alloc] init];
    });
    return _sharedRequestAPI;
}
- (instancetype)init {
    self = [super init];
    if (self) {
        NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
        configuration.HTTPMaximumConnectionsPerHost = 60;
        _manage = [[AFHTTPSessionManager alloc] initWithSessionConfiguration:configuration];
        //        _manager = [[AFHTTPSessionManager alloc] initWithBaseURL:[NSURL URLWithString:@""] sessionConfiguration:configuration];
    }
    return self;
}
//post请求
+ (void)postDataFromURLScheme:(NSString *)url
          parameterDictionary:(id)parameter
                      success:(SuccessBlock)success
                         fail:(FailBlock)fail
{
    NSParameterAssert(success);
    [[SYRequestAPI sharedAPI] postTradeFromURLScheme:url argumentsDictionary:parameter success:success fail:fail];
}

//白板得post
+ (void)bb_postDataFromURLSecheme:(NSString *)url
              parameterDictionary:(id)parameter
                          success:(SuccessBlock)success
                             fail:(FailBlock)fail
{
    NSParameterAssert(success);
    [[SYRequestAPI sharedAPI] bb_postDataFromURLSecheme:url parameterDictionary:parameter success:success fail:fail];
}
+ (void)bb_postTXDataFromURLSecheme:(NSString *)url
                parameterDictionary:(id)parameter
                            success:(SuccessBlock)success
                               fail:(FailBlock)fail
{
    NSParameterAssert(success);
    [[SYRequestAPI sharedAPI] bb_postTXDataFromURLSecheme:url parameterDictionary:parameter success:success fail:fail];
    
}
//get请求
+ (void)getDataFromURLScheme:(NSString *)url
         parameterDictionary:(NSDictionary *)parameter
                     success:(SuccessBlock)success
                        fail:(FailBlock)fail
{
    NSParameterAssert(success);
    [[SYRequestAPI sharedAPI] getDataFromURLScheme:url argumentsDictionary:parameter success:success fail:fail];
}
//推送调用的接口
+ (void)postPushFromUrlScheme:(NSString *)url
                parameterDict:(NSDictionary *)parameter
                      success:(SuccessBlock)success
                         fail:(FailBlock)fail
{
    NSParameterAssert(success);
    [[SYRequestAPI sharedAPI] postPushFromUrlScheme:url parameterDict:parameter success:success fail:fail];
}

+ (void)uploadWithUrl:(NSString *)url
           parameters:(id)parameters
               images:(NSArray *)images
                 name:(NSString *)name
             fileName:(NSString *)fileName
             progress:(NSString *)progress
              success:(SuccessBlock)success
                 fail:(FailBlock)fail
{
    NSParameterAssert(success);
    [[SYRequestAPI sharedAPI] uploadWithUrl:url parameters:parameters images:images name:name fileName:fileName progress:name success:success fail:fail];
}
+(void)creatingUserHeaderUpdateFile:(NSArray *)file
          fileType:(NSString *)fileType
           fileBusinessType:(NSString *)business
          fileName:(NSString *)FileName
           success:(SuccessBlock)success
            fail:(FailBlock)fail
{
    NSParameterAssert(success);
    [[SYRequestAPI sharedAPI] creatingUserHeaderUpdateFile:file fileType:fileType fileBusinessType:business fileName:fileType success:success fail:fail];
    
}
- (void)postPushFromUrlScheme:(NSString *)url
                parameterDict:(NSDictionary *)parameter
                      success:(SuccessBlock)success
                         fail:(FailBlock)fail
{
    
    NSMutableURLRequest *request = nil;
    if ([url containsString:@"External/PushMessage"]) { //
        NSString *parm = @"46cc468df60c961d8da2326337c7aa58";
        
        request = [[AFJSONRequestSerializer serializer] requestWithMethod:@"POST" URLString:url parameters:parameter error:nil];
        [request setValue:parm forHTTPHeaderField:@"Token"];
        [request setValue:@"pc" forHTTPHeaderField:@"platform"];
        [request setValue:@"" forHTTPHeaderField:@"version"];
    } else {
        request = [[AFJSONRequestSerializer serializer] requestWithMethod:@"POST" URLString:url parameters:parameter error:nil];
    }
    
    
    NSURLSessionTask *task = [_manage dataTaskWithRequest:request completionHandler:^(NSURLResponse * _Nonnull response, id  _Nullable responseObject, NSError * _Nullable error) {
        if (error) { //请求失败
            
            fail(error);
        } else {
            if ([responseObject[@"code"] integerValue] == 1101 || [responseObject[@"Code"] integerValue] == 1) { //成功
                success(responseObject);
            } else {
                
                fail(error);
            }
        }
    }];
    
    [task resume];
    
}

- (void)bb_postTXDataFromURLSecheme:(NSString *)url
                parameterDictionary:(id)parameter
                            success:(SuccessBlock)success
                               fail:(FailBlock)fail {
    NSString *urlStr = [NSString stringWithFormat:@"%@%@",kBBTMBaseApiUrl,url];
    NSMutableURLRequest *request = nil;
    if ([url containsString:@"GetImInfo"] ) { //请求腾讯im信息
        request = [[AFJSONRequestSerializer serializer] requestWithMethod:@"POST" URLString:urlStr parameters:nil error:nil];
        NSDictionary *dict = (NSDictionary *)parameter;
        NSString *parmeter = dict[@"token"];
        [request setValue:parmeter forHTTPHeaderField:@"token"];
    } else {
        request = [[AFJSONRequestSerializer serializer] requestWithMethod:@"POST" URLString:urlStr parameters:parameter error:nil];
    }
    NSURLSessionTask *task = [_manage dataTaskWithRequest:request completionHandler:^(NSURLResponse * _Nonnull response, id  _Nullable responseObject, NSError * _Nullable error) {
        if (error) { //请求失败
            
            fail(error);
        } else {
            if ([responseObject[@"code"] integerValue] == 1101 || [responseObject[@"Code"] integerValue] == 1 || [responseObject[@"code"] integerValue] == 1) { //成功
                success(responseObject);
            } else {
                
                fail(error);
            }
        }
    }];
    
    [task resume];
}

- (void) bb_postDataFromURLSecheme:(NSString *)url
               parameterDictionary:(id)parameter
                           success:(SuccessBlock)success
                              fail:(FailBlock)fail {
    NSString *urlStr = nil;
    
    if ([url containsString:@"GetTutorClassUserInfo"]) {
       urlStr = [NSString stringWithFormat:@"%@%@%@",kPCBaseApiURL,@"TutorService.svc/",url];
    } else if ([url containsString:@"http://"]) {
        urlStr = url;
    } else {
        urlStr = [NSString stringWithFormat:@"%@%@",kBBCMBaseApiURL,url];
    }
    
    NSMutableURLRequest *request = nil;
    if ([url isEqualToString:@"GetImInfo"] || [url isEqualToString:@"GetCloudPlaySign"]) { //请求腾讯im信息
        request = [[AFJSONRequestSerializer serializer] requestWithMethod:@"POST" URLString:urlStr parameters:nil error:nil];
        NSDictionary *dict = (NSDictionary *)parameter;
        NSString *parmeter = dict[@"token"];
        [request setValue:parmeter forHTTPHeaderField:@"token"];
    } else {
        request = [[AFJSONRequestSerializer serializer] requestWithMethod:@"POST" URLString:urlStr parameters:parameter error:nil];
    }
    
    
    NSURLSessionTask *task = [_manage dataTaskWithRequest:request completionHandler:^(NSURLResponse * _Nonnull response, id  _Nullable responseObject, NSError * _Nullable error) {
        if (error) { //请求失败
            
            fail(error);
        } else {
            if ([responseObject[@"code"] integerValue] == 1101 || [responseObject[@"Code"] integerValue] == 1) { //成功
                success(responseObject);
            } else {
                
                fail(error);
            }
        }
    }];
    
    [task resume];
}

//需要加入 请求头 touken 的post请求
- (void)postTradeFromURLScheme:(NSString *)urlScheme argumentsDictionary:(id)arguments success:(SuccessBlock)success fail:(FailBlock)fail {
    NSString *urlStr = [NSString stringWithFormat:@"%@%@",kCMBaseApiURL,urlScheme];
    
    NSMutableURLRequest *request = [[AFJSONRequestSerializer serializer] requestWithMethod:@"POST" URLString:urlStr parameters:nil error:nil];
    NSLog(@"头部 %@",request.allHTTPHeaderFields);
    [AFJSONResponseSerializer serializer];
    [self addFatherParameters:request dictionary:arguments url:urlScheme];
    NSURLSessionDataTask *dataTask = [_manage dataTaskWithRequest:request completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
        if (error) { //请求失败
           
            NSError *syError = [NSError errorWithDomain:error.domain code:[responseObject[@"code"] integerValue] message:[NSString errorMessageWithCode:[responseObject[@"code"] integerValue]]];
            fail(syError);
            //如果是token失效需要重新登录
           
        } else {
            if ([responseObject[@"code"] integerValue] == 10000) { //成功
                success(responseObject);
            } else {
                if([responseObject[@"code"] isEqualToString:@"10003"]){
                    //token失效
                    [USERDEFAL removeObjectForKey:TokenDefalut];
                    [USERDEFAL removeObjectForKey:RYUserPathDefalut];
                    [USERDEFAL removeObjectForKey:RYUserNameDefalut];
                    [USERDEFAL removeObjectForKey:RYUserIdDefalut];
                    [USERDEFAL removeObjectForKey:RYTokenDefalut];
                    [USERDEFAL removeObjectForKey:RYIMidIDDefalut];
                    AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
                    [appDelegate.friendsArray removeAllObjects];
                    [appDelegate.groupsArray removeAllObjects];
                    [appDelegate.AllArray removeAllObjects];
                    [[RCIMClient sharedRCIMClient] disconnect];

                    [self goBackLoginView];
                }
                
                NSError *syError = [NSError errorWithDomain:responseObject[@"msg"] code:[responseObject[@"code"] integerValue] message:[NSString errorMessageWithCode:[responseObject[@"code"] integerValue]]];
                fail(syError);
            }
        }
    }];
    [dataTask resume];
    
}
#pragma mark - 重回登录
- (void)goBackLoginView{
    LoginViewController *login = [[LoginViewController alloc]init];
    [UIApplication sharedApplication].keyWindow.rootViewController = [[UINavigationController alloc]initWithRootViewController:login];
    [[UIApplication sharedApplication].keyWindow makeKeyAndVisible];
}
//GET 请求
- (void)getDataFromURLScheme:(NSString *)urlScheme
         argumentsDictionary:(NSDictionary *)arguments
                     success:(SuccessBlock)success
                        fail:(FailBlock)fail
{
    NSString *urlStr = [NSString stringWithFormat:@"%@%@",kCMBaseApiURL,urlScheme];
    NSMutableURLRequest *request = [[AFJSONRequestSerializer serializer] requestWithMethod:@"GET" URLString:urlStr parameters:nil error:nil];
    [self addFatherParameters:request dictionary:arguments url:urlScheme];
    NSURLSessionDataTask *dataTask = [_manage dataTaskWithRequest:request completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
        if (error) { //请求失败
            fail(error);
        } else {
            if ([responseObject[@"code"] integerValue] == 10000) { //成功
                NSLog(@"%@",responseObject);
                success(responseObject);
            } else {
                NSError *syError = [NSError errorWithDomain:responseObject[@"msg"] code:[responseObject[@"code"] integerValue] message:[NSString errorMessageWithCode:[responseObject[@"code"] integerValue]]];
                fail(syError);
            }
        }
    }];
    [dataTask resume];
}
//添加Headers
- (void)addFatherParameters:(NSMutableURLRequest *)request dictionary:(NSDictionary *)dict  url:(NSString *)url {
    NSString *token;//token  登录时候不添加token,为空 也就是没有token
    if ([url containsString:@"login/LoginService.svc/Login"]||[url containsString:@"SetPassword"]) {
        token = @"";
    } else {
        token = Token;
    }
    NSLog(@"输出Token %@",Token);
    //获取app版本号
    NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
    NSString *app_Version = [infoDictionary objectForKey:@"CFBundleShortVersionString"];
    //获取集团账号
    NSString *groupId = @"1";
    
    
    //添加token 有可能需要在token前边添加base 预留，所以组合填写
    [request setValue:[NSString stringWithFormat:@"%@",token] forHTTPHeaderField:@"token"];
    //添加版本号
    [request setValue:[NSString stringWithFormat:@"%@",app_Version] forHTTPHeaderField:@"version"];
    //平台
    [request setValue:@"2" forHTTPHeaderField:@"platform"];
    
    [request setValue:groupId forHTTPHeaderField:@"groupId"];

//    NSString *jsonStr = [NSObject convertToJsonData:dict];
    NSString *jsonStr = @"";
    
    if (dict == nil) {
        jsonStr = @"";
    }else{
        jsonStr = [NSObject convertToJsonData:dict];
        
    }
    //128
    NSString *aesStr = [ZCSecureTools encrypt:jsonStr password:@"697CAF7DE44A4326931FCB5B88E35747"];
    NSLog(@"加密前的参数  %@",jsonStr);
    NSLog(@"加密后的参数  %@",aesStr);
    [request setHTTPBody:[aesStr dataUsingEncoding:NSUTF8StringEncoding]];
}

#pragma mark - 白板服务请求




+ (void)uploadFileRequest:(NSArray *)image andURL:(NSString *)postUrl andParama:(NSDictionary *)parama andAcountID:(NSString *)acountID success:(SuccessBlock)success fail:(FailBlock)fail{
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    //ContentType设置
    
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/html",@"image/jpeg",@"image/png",@"application/octet-stream",@"text/json",nil];
    
    
    
    manager.requestSerializer= [AFHTTPRequestSerializer serializer];
    
    manager.responseSerializer= [AFHTTPResponseSerializer serializer];
    
    NSString *urlStr = postUrl;
    
    [manager POST:urlStr parameters:parama constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        
                for (NSInteger i = 0; i <image.count ; i ++) {
                    NSString *file = image[i];
                    
//                    NSData *data = [NSData dataWithContentsOfFile:file];;
//                    
//                    NSString *nameFile = [NSString stringWithFormat:@"ios/%@_userHeader_%ld.png",acountID,i];
                    
                    NSData *imageData = UIImageJPEGRepresentation(image[i], 0.5f);
                    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
                    formatter.dateFormat = @"yyyyMMddHHmm";
                    NSString *fileStr = [formatter stringFromDate:[NSDate date]];
                    NSString *fileName = [NSString stringWithFormat:@"%@%ld.%@",fileStr,i,@"jpg"];
                    [formData appendPartWithFileData:imageData
                                                name:@"weike"
                                            fileName:fileName
                                            mimeType:@"jpg"];
                }


        
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        
        
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        
        NSDictionary * dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:nil];
        
        NSLog(@"上传成功%@",dic);
        
        for (NSInteger i = 0; i <image.count ; i ++) {
            NSString *file = image[i];
            [[NSFileManager defaultManager] removeItemAtPath:file error:nil];
        }
        
        if ([dic[@"code"] integerValue] == 1101) {
            if (success) {
                success(dic);
            }
        } else {
            NSError *syError = [NSError errorWithDomain:responseObject[@"msg"] code:[responseObject[@"code"] integerValue] message:[NSString errorMessageWithCode:[responseObject[@"code"] integerValue]]];
            fail(syError);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        NSLog(@"上传失败%@",error);
        if (fail) {
            fail(error);
        }
        
    }];
    
}


- (void)uploadWithUrl:(NSString *)url
           parameters:(id)parameters
               images:(NSArray *)images
                 name:(NSString *)name
             fileName:(NSString *)fileName
             progress:(NSString *)progress
              success:(SuccessBlock)success
                 fail:(FailBlock)fail
{
    
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    //ContentType设置
    
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/html",@"image/jpeg",@"image/png",@"application/octet-stream",@"text/json",nil];
    
    
    
    manager.requestSerializer= [AFHTTPRequestSerializer serializer];
    
    manager.responseSerializer= [AFHTTPResponseSerializer serializer];
    
    NSString *urlStr = url;
    
    [manager POST:urlStr parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        
        for (NSInteger i = 0; i <images.count ; i ++) {
            if ([progress isEqualToString:@"1"]) {
                
                        NSURL *url = images[i];
                                                        
                                                        
                        NSString *nameFile = [NSString stringWithFormat:@"%@_userHeader_%ld.MP4",fileName,i];
                        NSData *data =[NSData dataWithContentsOfFile:url.path];
                                                        //上传的参数(上传图片，以文件流的格式)
                        [formData appendPartWithFileData:data
                                                                        name:@"weike"
                                                                        fileName:nameFile
                                                                        mimeType:@"application/octet-stream"];
                            //                [formData appendPartWithFileURL:url name:nameFile error:nil];
            }else{
                            NSString *file = images[i];
                            
                            NSData *data = [NSData dataWithContentsOfFile:file];;
                            
                            NSString *nameFile = [NSString stringWithFormat:@"ios/%@_userHeader_%ld.png",fileName,i];
                            
                            //上传的参数(上传图片，以文件流的格式)
                //            [formData appendPartWithFileData:data
                //                                        name:nameFile
                //                                    fileName:file
                //                                    mimeType:@"image/*"];
                            [formData appendPartWithFileURL:[NSURL fileURLWithPath:file] name:nameFile error:nil];
            }

        }
        
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        
        
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        
        NSDictionary * dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:nil];
        
        NSLog(@"上传成功%@",dic);
        
        for (NSInteger i = 0; i <images.count ; i ++) {
            NSString *file = images[i];
            [[NSFileManager defaultManager] removeItemAtPath:file error:nil];
        }
        
        if ([dic[@"code"] integerValue] == 1101) {
            if (success) {
                success(dic);
            }
        } else {
            NSError *syError = [NSError errorWithDomain:responseObject[@"msg"] code:[responseObject[@"code"] integerValue] message:[NSString errorMessageWithCode:[responseObject[@"code"] integerValue]]];
            fail(syError);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        NSLog(@"上传失败%@",error);
        if (fail) {
            fail(error);
        }
        
    }];
}

-(void)creatingUserHeaderUpdateFile:(NSArray *)file
                      fileType:(NSString *)fileType
              fileBusinessType:(NSString *)business
                    fileName:(NSString *)FileName
                       success:(SuccessBlock)success
                          fail:(FailBlock)fail
{

    NSDictionary *dict = @{@"fileNames":FileName};
    
    NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:@"POST" URLString:@"http://image.31waiyu.com/HttpUpload/HttpFileUpload.ashx" parameters:dict constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        
        for (NSInteger i = 0; i < file.count; i ++) {
            if ([fileType isEqualToString:@"1"]) {//图片
                NSData *imageData = UIImageJPEGRepresentation(file[i], 0.5f);
                NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
                formatter.dateFormat = @"yyyyMMddHHmm";
                NSString *fileStr = [formatter stringFromDate:[NSDate date]];
                NSString *fileName = [NSString stringWithFormat:@"%@%ld.%@",fileStr,i,@"jpg"];
                [formData appendPartWithFileData:imageData
                                            name:@"headimg"
                                        fileName:fileName
                                        mimeType:@"jpg"];
            } else if ([fileType isEqualToString:@"2"]) {//视频
                
                NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
                formatter.dateFormat = @"yyyyMMddHHmm";
                NSString *fileStr = [formatter stringFromDate:[NSDate date]];
                NSString *fileName = [NSString stringWithFormat:@"%@%ld.%@",fileStr,i,@"MP4"];
//                [formData appendPartWithFileData:file[i]
//                                            name:@"headimg"
//                                        fileName:fileName
//                                        mimeType:@"MP4"];
                
//                dataWithContentsOfFile:(NSString *)path
                NSData*fileData = [NSData dataWithContentsOfURL:file[i]];

                [formData appendPartWithFileData:fileData name:@"uploadFileList" fileName:fileName mimeType:@"application/octet-stream"];

            } else if ([fileType isEqualToString:@"3"]) {//文档
                
            }
            
        }
    } error:nil];
    
    NSURLSessionUploadTask *uploadTask;
    uploadTask = [_manage uploadTaskWithStreamedRequest:request progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } completionHandler:^(NSURLResponse * _Nonnull response, id  _Nullable responseObject, NSError * _Nullable error) {
        if (error) { //请求失败
            fail(error);
        } else {
            if ([responseObject[@"code"] integerValue] == 1) { //成功
                success(responseObject[@"data"]);
            } else {
                fail(error);
            }
        }
    }];
    
    [uploadTask resume];
}
@end












